/****************************************************************************
 * Copyright (c) 2008, 2009 Andreas Unger and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Andreas Unger - initial API and implementation 
 ****************************************************************************/

package org.eclipselabs.damos.expressions.util;

import org.eclipselabs.damos.dml.BooleanDataType;
import org.eclipselabs.damos.dml.DMLFactory;
import org.eclipselabs.damos.dml.DataType;
import org.eclipselabs.damos.dml.FixedPointDataType;
import org.eclipselabs.damos.dml.FloatingPointDataType;
import org.eclipselabs.damos.dml.FloatingPointFormat;


/**
 * @author Andreas Unger
 *
 */
public class ExpressionsUtil {
	
	public static String dataTypeToString(DataType dataType) {
		if (dataType instanceof BooleanDataType) {
			return "boolean";
		}
		if (dataType instanceof FloatingPointDataType) {
			return "double";
		}
		if (dataType instanceof FixedPointDataType) {
			FixedPointDataType fixedPointDataType = (FixedPointDataType) dataType;
			return (fixedPointDataType.isSigned() ? "Q" : "uQ") + fixedPointDataType.getIntegerLength() + "." + fixedPointDataType.getFractionalLength();
		}
		return null;
	}

	public static DataType parseDataTypeExpression(String s) {
		if ("boolean".equals(s)) {
			return DMLFactory.eINSTANCE.createBooleanDataType();
		}
		if ("double".equals(s)) {
			FloatingPointDataType dataType = DMLFactory.eINSTANCE.createFloatingPointDataType();
			dataType.setFormat(FloatingPointFormat.BINARY64);
			return dataType;
		}
		if (s.matches("\\Au?Q\\d+\\.\\d+\\z")) {
			String[] parts = s.substring(s.charAt(0) == 'u' ? 2 : 1).split("\\.");
			FixedPointDataType dataType = DMLFactory.eINSTANCE.createFixedPointDataType();
			dataType.setSigned(s.charAt(0) != 'u');
			dataType.setIntegerLength(Integer.parseInt(parts[0]));
			dataType.setFractionalLength(Integer.parseInt(parts[1]));
			return dataType;
		}
		return null;
	}

	public static double[] parseListExpression(String expression) {
		if (!expression.matches("\\A\\s*\\[.*\\]\\s*\\z")) {
			throw new IllegalArgumentException("Illegal expression");
		}
		String[] elements = expression.replaceAll("\\A.*\\[|\\].*\\z|\\s\\s+", " ").trim().split("\\s");
		double[] result = new double[elements.length];
		try {
			for (int i = 0; i < elements.length; ++i) {
				result[i] = Double.parseDouble(elements[i]);
			}
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException(e);
		}
		return result != null ? result : new double[0];
	}

}
